interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: any;
  loading?: boolean;
}

interface ResponseData<T = any> {
  statusCode: number;
  data?: T;
  message: string;
}

export interface ResponseResult<T = any> {
  status: number;
  msg: string;
  data?: T;
  token?:string
}

// 基础配置
const BASE_URL = 'https://xiaomai.yipinghaowu.com/api';
const TOKEN_KEY = '';

import { useUserStore } from '@/utils/pinia'
import type { UserStore } from '@/utils/pinia'


const userStore: UserStore = useUserStore()

// 请求封装
const request = <T>(options: RequestOptions): Promise<T> => {
  const token = userStore.token;
  console.log(options, 'options')
  
  
  // 显示加载框
  if (options.loading !== false) {
    uni.showLoading({ title: '加载中...' });
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Token': token ? token : ''
      },
      success: (res: any) => {
        console.log(token,options, '1111')
        console.log(res, '000000000000000')
        const response = res as ResponseData<T>;
        
        // 请求成功
        if (response.statusCode === 200) {
          resolve(response.data as T);
        }
        // token 失效
        else if (response.statusCode === 401) {
          uni.removeStorageSync(TOKEN_KEY);
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          // 跳转登录页
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/login/login' });
          }, 1500);
          reject(response);
        }
        // 其他错误
        else {
          uni.showToast({
            title: response.message || '请求失败',
            icon: 'none'
          });
          reject(response);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
        reject(err);
      },
      complete: () => {
        if (options.loading !== false) {
          uni.hideLoading();
        }
      }
    });
  });
};

// 导出请求方法
export const http = {
  get: <T>(url: string, data?: any) => {
    return request<T>({ url, method: 'GET', data });
  },
  post: <T>(url: string, data?: any) => {
    return request<T>({ url, method: 'POST', data });
  },
  put: <T>(url: string, data?: any) => {
    return request<T>({ url, method: 'PUT', data });
  },
  delete: <T>(url: string, data?: any) => {
    return request<T>({ url, method: 'DELETE', data });
  }
};
